package demoMod.stsconsole.helpers;

import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import demoMod.stsconsole.ConsoleEntry;
import demoMod.stsconsole.interfaces.CustomSavable;

import java.io.*;
import java.util.Map;

/**
 * 操作存档文件
 * 读档时如果没有存档文件则新开局
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
public class SaveHelper {
    public static boolean saveExists() {
        return new File("saves/save.json").exists();
    }

    public static void save() {
        File dir = new File("saves/");
        if (!dir.exists()) {
            dir.mkdir();
        }
        File saveFile = new File("saves/save.json");
        if (saveFile.exists()) {
            saveFile.delete();
        }
        try {
            saveFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> saveData = ConsoleEntry.rootSaver.onSave();

        try (Writer writer = new FileWriter(saveFile)) {
            writer.write(CustomSavable.saveFileGson.toJson(saveData));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void load() {
        File saveFile = new File("saves/save.json");
        ConsoleEntry.subscribers.clear();
        if (saveFile.exists()) {
            try {
                Map<String, Object> saveData = CustomSavable.saveFileGson.fromJson(new InputStreamReader(new FileInputStream(saveFile)), new TypeToken<Map<String, JsonElement>>(){}.getType());
                ConsoleEntry.rootSaver.onLoad(saveData);
            } catch (IOException e) {
                deleteSave();
                e.printStackTrace();
            }
        } else {
            ConsoleEntry.rootSaver.onLoad(null);
        }
    }

    public static void deleteSave() {
        File saveFile = new File("saves/save.json");
        if (saveFile.exists()) {
            saveFile.delete();
        }
    }
}
